package ctn.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileUtil {
	public static void copyFile(File fromFile,File toFile){
		FileInputStream in;
		try {
			int count=1;
			while(toFile.exists()){
				toFile=new File(toFile.getParent()+"/"+(count++)+"_"+toFile.getName());
			}
			toFile.createNewFile();
			in = new FileInputStream(fromFile);
	
		FileOutputStream out = new FileOutputStream(toFile);
		FileChannel inC = in.getChannel();
		FileChannel outC = out.getChannel();
		int length = 2097152;
		int i = 0;

			while (true) {
				if (inC.position() == inC.size()) {
					inC.close();
					outC.close();
				}
				if ((inC.size() - inC.position()) < 20971520)
					length = (int) (inC.size() - inC.position());
				else
					length = 20971520;
				inC.transferTo(inC.position(), length, outC);
				inC.position(inC.position() + length);
				i++;
			}
		} catch (FileNotFoundException e) {
			//e.printStackTrace();
		} catch (IOException e) {
			//e.printStackTrace();
		}
	}
	public static void cutFolder(File fromFolder,File toFolder){
		if(fromFolder.isDirectory()){
			int count=1;
			while(toFolder.exists()){
				toFolder=new File(toFolder.getParent()+"/"+(count++)+"_"+toFolder.getName());
			}
			toFolder.mkdir();
			File[] files=fromFolder.listFiles();
			for(File file:files){
				File tofile=new File(toFolder.getAbsolutePath()+"/"+file.getName());
				cutFolder(file,tofile);
			}
		}else{
			cutFile(fromFolder,toFolder);
		}
	}
	public static void cutFile(File fromFile,File toFile){
		copyFile(fromFile,toFile);
		fromFile.delete();
	}
}
